<template>
  <div>
    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="40%" v-dialogDrag append-to-body>
      <el-form ref="formRef" :model="formData" :rules="formRules" v-loading="formLoading" label-width="80px">
        <el-form-item v-for="(item, index) in formData.inputRows"
                      :key="index"
                      :label="'编码 ' + (index + 1)"
                      :prop="'inputRows.' + index + '.value'"
                      :rules="formRules.items[0].value">
          <div style="display: flex">
            <el-input v-model="item.value" placeholder="请输入托盘码/RFID编码" style="width: 200px; margin-right: 10px;"></el-input>
            <el-button v-if="index > 0" type="danger" plain icon="el-icon-minus" @click="removeItem(index)">删除</el-button>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="warning" plain icon="el-icon-plus" @click="addInputRow">添加</el-button>
        <el-button type="primary" @click="submitForm" :disabled="formLoading">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as ReceiveOrderApi from '@/api/hs/receiveorder';
import {DICT_TYPE} from "@/utils/dict";

export default {
  name: "ReceiveOrderForm",
  computed: {
    DICT_TYPE() {
      return DICT_TYPE
    }
  },
  components: {},
  data() {
    return {
      // 弹出层标题
      dialogTitle: "",
      // 是否显示弹出层
      dialogVisible: false,
      // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
      formLoading: false,
      // 表单参数
      formData: {
        // 初始输入行数据
        inputRows: [{value: ''}],
      },
      formRules: {
        items: [
          {
            value: [
              {required: true, message: '编码不能为空', trigger: 'blur'}
            ]
          }
        ]
      }
    };
  },
  methods: {
    /** 打开弹窗 */
    async open() {
      this.dialogVisible = true;
      this.reset();
      this.dialogTitle = "收货";
    },
    /** 添加新的输入行 */
    addInputRow() {
      this.formData.inputRows.push({value: ''});
    },
    /** 删除指定索引的输入行 */
    removeItem(index) {
      if (index === 0) {
        return
      }
      this.formData.inputRows.splice(index, 1);
    },
    /** 提交按钮 */
    async submitForm() {
      // 校验主表
      await this.$refs["formRef"].validate();
      this.formLoading = true;
      try {
        const codeList = this.formData.inputRows.map(item => {
          return item.value
        });
        const data = {
          codeList: codeList,
          receiveType: 2
        }
        // 添加的提交
        await ReceiveOrderApi.createReceiveOrder(data);
        this.$modal.msgSuccess("收货成功");
        this.dialogVisible = false;
        this.$emit('success');
      } finally {
        this.formLoading = false;
      }
    },
    /** 表单重置 */
    reset() {
      this.formData.inputRows = [{value: ''}]
    }
  }
};
</script>
